package com.zrb.mobile.register;

import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import com.zrb.mobile.BuildConfig;
import com.zrb.mobile.MainTabActivity;
import com.zrb.mobile.R;
import com.zrb.mobile.RegisterBaseActivity;
 
import com.zrb.mobile.adapter.model.CollectionDtos;
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.common.FavoritehistoryDao;
import com.zrb.applib.utils.LocalUserInfo;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.register.UserRegister;
import com.zrb.mobile.ui.ClearEditTextEx;
import com.zrb.mobile.ui.ClearEditTextEx.onTextCorrectListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

public class User_phone_login extends RegisterBaseActivity implements
		OnClickListener, onTextCorrectListener {
	private static final String LOG_TAG = "User_phone_login";
	ImageView btnAccountclear, btnPwdclear 
			    ;
	AutoCompleteTextView editTextname;
	EditText editTextpwd;
	Tip progTip;
	CheckBox isRemember;
	private SharedPreferences.Editor editor;
	private SharedPreferences sharedPreferences;
 
 
	private Button loginButton;
	private TextView forgetPSW, right_title;
	private TextView register;
	// public String ACTION_NAME = "discover_main";
	private boolean isforResult = false;
	private boolean isGuidelogin = false;
	public String ACTION_NAME_FOUR = "discover_detail_content";
	ClearEditTextEx userphone;
	ClearEditTextEx userpwd;
	
	
	public static void launch (Activity mActivity,boolean isForResult){
		
		 if(mActivity==null) return;
		 Intent it = new Intent(mActivity, User_phone_login.class);
		 it.putExtra("forResult", isForResult );
 		 if(isForResult)  mActivity.startActivityForResult(it, 101);
		 else
			 mActivity.startActivity(it);
	}
	
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		Log.d(LOG_TAG,"onCreate");
		setContentView(R.layout.u_center_login);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			isforResult = this.getIntent().getBooleanExtra("forResult", false);
			isGuidelogin = this.getIntent()
					.getBooleanExtra("guidelogin", false);
		}
		initView();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("forResult", isforResult);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		isforResult = savedInstanceState.getBoolean("forResult", false);
	}

	@Override
	protected void initView() {

		super.initView();
 		registerBoradcastReceiver1();
		right_title = (TextView) this.findViewById(R.id.right_title);
		right_title.setVisibility(View.VISIBLE);
		right_title.setOnClickListener(this);

	 
		userphone= (ClearEditTextEx) findViewById(R.id.layout_username);
		userphone.setInputType(1);
		userphone.setOnTextCorrectListener(this);
 		
		
		
		userpwd= (ClearEditTextEx) findViewById(R.id.layout_code);
		userpwd.setInputType(2);
		userpwd.setOnTextCorrectListener(onpwdCorrect);
		
		
		loginButton = (Button) findViewById(R.id.login_btn);
		forgetPSW = (TextView) findViewById(R.id.txt_forgetpwd);
		register = (TextView) findViewById(R.id.txt_title);
		this.findViewById(R.id.login_btn).setOnClickListener(this);
		this.findViewById(R.id.txt_forgetpwd).setOnClickListener(this);
		// forgetPSW.setText(Html.fromHtml("<u>忘记密码?</u>"));
		forgetPSW.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
		forgetPSW.getPaint().setAntiAlias(true);// 抗锯齿

		TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setText("登 录");
		View lefticon = this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);

	

	/*	editPassWord
				.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (!TextUtils.isEmpty(editPassWord.getText())) {
							if (editPassWord.getText().length() != 0
									&& !hasFocus
									&& CommonUtil.checkPassword(editPassWord
											.getText().toString())) {
								pwd_btn_clean.setVisibility(View.GONE);
								phone_btn_right1.setVisibility(View.VISIBLE);
							} else {
								pwd_btn_clean.setVisibility(View.VISIBLE);
								phone_btn_right1.setVisibility(View.GONE);
							}
						}
					}
				});

		*/
 

		if (BuildConfig.DEBUG) {
			this.userphone.setText("13554142989");
			this.userpwd.setText("123456");
		}
	}

	@Override
	public void onTextCorrect(boolean isCorrect) {
		// TODO Auto-generated method stub
		if(!isCorrect) 	loginButton.setEnabled(false);
		else
 			loginButton.setEnabled(!userpwd.isEmpty());
 
	}
	
	onTextCorrectListener onpwdCorrect=new onTextCorrectListener(){

		@Override
		public void onTextCorrect(boolean isCorrect) {
			// TODO Auto-generated method stub
			
			CommonUtil.InfoLog("onpwdCorrect", isCorrect+"");
			if(!isCorrect) 	loginButton.setEnabled(false);
			else
	 			loginButton.setEnabled(!userphone.isEmpty());
		}
 	};
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.login_btn:
			user_Login();
			break;
		case R.id.txt_forgetpwd:
			Intent it2 = new Intent(this, UserFindPassword.class);
			startActivity(it2);
			break;
		case R.id.right_title:
			Intent it = new Intent(User_phone_login.this, UserRegister.class);
			startActivity(it);
			break;
	 
		}
	}

	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在登录中...", true,
					true);
		else
			progTip.Show("正在登录中...");
	}

	private void user_Login() {
		final String name = this.userphone.getContentValue();//.getText().toString();
		final String password = this.userpwd.getContentValue();
		if (TextUtils.isEmpty(name)) {
			initNotify("用户名不能为空");
			return;
		}
		if (TextUtils.isEmpty(password)) {
			initNotify("密码不能为空");
			return;

		}
		if (!CommonUtil.checkPassword(password)) {
			initNotify("密码不符合规则");
			return;
		}
		showloading();
		RequestParams param = new RequestParams();
		param.put("name", name);
		param.put("password", password);

		// String loginurlparms = "?name=" + name + "&password="+ password;
		ZrbRestClient.post("dologin", param, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				initNotify("服务端网络连接出错");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				String results = new String(arg2);
				Log.e("tag", results);
				try {
					Gson gson = new Gson();
					UserDtos tmpDto = gson.fromJson(results, UserDtos.class);
					if (tmpDto.res == 1) {
						AppSetting.curUser = tmpDto.data;
						AppSetting.curUser.pwd = password;
						LocalUserInfo.getInstance(User_phone_login.this)
								.saveUserInfo(tmpDto.data);
						// DemoApplication.getInstance().setUserAvatar(FileUtil.filePath+AppSetting.curUser.avatar);
						// CommonUtil.InfoLog("ffff",
						// FileUtil.filePath+AppSetting.curUser.avatar);
						if (isforResult)
							User_phone_login.this.setResult(RESULT_OK);
						else if (isGuidelogin) {
							Intent it = new Intent(User_phone_login.this, MainTabActivity.class);
							startActivity(it);
							User_phone_login.this.finish();
							return;

						}
						User_phone_login.this.finish();
						Intent intent1 = new Intent(
								Constants.Refresh_Find_mainlist);// ACTION_NAME
																	// =
																	// "discover_main";
						sendBroadcast(intent1);
						/*
						 * Intent intent2 = new Intent(ACTION_NAME_FOUR);
						 * sendBroadcast(intent2);
						 */

					} else {
						initNotify(tmpDto.msg);
					}
				} catch (Exception e) {
					initNotify(User_phone_login.this
							.getString(R.string.error_serverdata_loadfail));
				}

			}
		});
	}

	/**
	 * 判断某一个类是否存在任务栈里面
	 * 
	 * @return
	 */
	private boolean isExsitMianActivity(Class<?> cls) {
		Intent intent = new Intent(this, cls);
		ComponentName cmpName = intent.resolveActivity(getPackageManager());
		boolean flag = false;
		if (cmpName != null) { // 说明系统中存在这个activity
			ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
			List<RunningTaskInfo> taskInfoList = am.getRunningTasks(10); // ActivityManager.RunningTaskInfo
			for (RunningTaskInfo taskInfo : taskInfoList) {
				if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
					flag = true;
					break; // 跳出循环，优化效率
				}
			}
		}
		return flag;
	}

	private void refleshAttention() {
		showloading();

		// user/interest/news/all?zrb_front_ut=
		ZrbRestClient.get("collection/queryByType?zrb_front_ut="
				+ AppSetting.curUser.zrb_front_ut, null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						CommonUtil.showToast("网络超时,请重新连接",
								User_phone_login.this);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						String results = new String(arg2);
						// Log.e("tag",
						// results);{"res":1,"msg":null,"data":[147,146,148]}
						try {
							Gson gson = new Gson();
							CollectionDtos tmpDto = gson.fromJson(results,
									CollectionDtos.class);
							if (tmpDto.res == 1) {

								FavoritehistoryDao mfavoriteItemDao = new FavoritehistoryDao(
										User_phone_login.this);
								mfavoriteItemDao.resetIds(tmpDto.data);

								if (isforResult)
									User_phone_login.this.setResult(RESULT_OK);
								User_phone_login.this.finish();
							} else
								CommonUtil.showToast("fail:" + tmpDto.msg,
										User_phone_login.this);

						} catch (Exception e) {
							CommonUtil.showToast("fail:" + e.getMessage(),
									User_phone_login.this);
						}
					}
				});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver1);
	}

	public void registerBoradcastReceiver1() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Constants.Regin_Success_FINISH);
		// 注册广播,当注册成功，登录页面存在的时候就关闭
		registerReceiver(mBroadcastReceiver1, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();
			CommonUtil.InfoLog("action", action);
			if (action.equals(Constants.Regin_Success_FINISH)) {
				User_phone_login.this.finish();
			}

		}
	};
	

}
